import { apiInitializer } from "discourse/lib/api";

export default apiInitializer("1.0.0", () => {
  function parseHashForToken() {
    const hash = window.location.hash;
    if (!hash) return;
    const params = new URLSearchParams(hash.replace('#', ''));
    const token = params.get('access_token');
    if (token) {
      localStorage.setItem('gitee_access_token', token);
      window.history.replaceState({}, document.title, window.location.pathname);
    }
  }
  parseHashForToken();

  window.GiteeAuth = {
    getToken() {
      return localStorage.getItem('gitee_access_token');
    },
    clear() {
      localStorage.removeItem('gitee_access_token');
    },
    startOAuth() {
      const clientId = settings.client_id;
      const redirectUri = settings.redirect_uri || window.location.origin + '/';
      const scope = 'user_info projects issues';
      const authUrl = `https://gitee.com/oauth/authorize?client_id=${clientId}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=token&scope=${encodeURIComponent(scope)}`;
      window.location.href = authUrl;
    }
  }
});